﻿using Common.Library;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Network.Library;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Diagnostics;
using System.Reflection;
using System.Web;
using Tool.Model;
using Validate.Library;

namespace Web.Manage
{
    /// <summary>
    /// 控制器基类
    /// </summary>
    public class BaseController : Controller
    {
        /// <summary>
        /// HttpContext对象
        /// </summary>
        public static HttpContext HttpHelper => HttpContextHelper.HttpContext;

        /// <summary>
        /// 请求数据
        /// </summary>
        public string requestInfo { get; set; }

        /// <summary>
        /// 处理action前
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (filterContext.HttpContext.Request.IsAjaxRequest() && HttpHelper.Request.Method.ToUpper() == "POST")
            {
                try
                {

                    string param = string.Empty;
                    if (HttpHelper.Request.ContentLength != 0)
                    {
                        if (HttpHelper.Request.Form.ContainsKey("page") && HttpHelper.Request.Form.ContainsKey("limit"))
                        {
                            string parameters = HttpUtility.UrlDecode(HttpHelper.Request.Form.ContainsKey("parameters") && HttpHelper.Request.Form["parameters"] != "" ? HttpHelper.Request.Form["parameters"].ToString() : "");

                            string field = HttpHelper.Request.Form["field"].ToString().IsNotNullOrEmpty() ? HttpHelper.Request.Form["field"].ToString() : "gCode";
                            string order = HttpHelper.Request.Form["order"].ToString().IsNotNullOrEmpty() ? HttpHelper.Request.Form["order"].ToString() : "asc";

                            requestInfo = $"{{\"page\":\"{HttpHelper.Request.Form["page"].ToString()}\"" +
                                $",\"limit\":\"{HttpHelper.Request.Form["limit"].ToString()}\"" +
                                $",\"field\":\"{field}\"" +
                                $",\"order\":\"{order}\"" +
                                $",\"parameters\":{(parameters.IsNotNullOrEmpty() ? parameters : ("\"" + parameters + "\""))}}}";
                        }
                        else if (HttpHelper.Request.Form.ContainsKey("param"))
                        {
                            requestInfo = HttpUtility.UrlDecode(HttpHelper.Request.Form["param"].ToString());
                        }
                    }
                }
                catch (Exception ex)
                {
                    MethodBase methodName = new StackTrace().GetFrame(1).GetMethod();
                    NLogHelper.LogError($"\r\n错误位置:\r\n方法名:{methodName}", ex);
                    throw ex;
                }
            }
            base.OnActionExecuting(filterContext); 
        }

        /// <summary>
        /// 接口专用转换（解压）数据
        /// </summary>
        /// <typeparam name="T">返回类型</typeparam>
        /// <param name="json">json数据</param>
        /// <returns>处理结果</returns>
        public T DeserializeRequestData<T>() where T : class, new()
        {

            var message = new T();
            if (!requestInfo.IsNullOrEmpty())
            {
                try
                {
                    message = JsonConvert.DeserializeObject<T>(requestInfo);
                }
                catch//(Exception ex)
                {
                    throw new ValidateException("参数类型错误！");
                }
                message.Validate();
            }
            return message;

        }


        #region 输出到客户端

        /// <summary>
        /// 输出到客户端
        /// </summary>
        /// <returns></returns>
        protected ContentResult ReturnContent<T>(ResultJsonInfo<T> data)
        {
            MethodBase methodName = new StackTrace().GetFrame(1).GetMethod();
            if (!data.Success)
            {
                if (!data.Excep.GetType().ToString().Contains("ValidateException"))
                {
                    NLogHelper.LogError($"\r\n错误位置:\r\n所属类:{this.GetType().Name}\r\n方法名:{ methodName}\r\n{data.Msg}", data.Excep);
                    data.Msg = "系统错误！";
                }
                else
                {
                    data.Msg = data.Excep.Message.ToString();
                }
            }
            string resultStr = JsonConvert.SerializeObject(data, new IsoDateTimeConverter() { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" });
            return Content(resultStr);
        }

        /// <summary>
        /// 输出到客户端
        /// </summary>
        /// <param name="data"></param>
        protected FileContentResult ReturnFile(ResultFileContent data)
        {
            MethodBase methodName = new StackTrace().GetFrame(1).GetMethod();
            if (!data.Success)
            {
                if (!data.Excep.GetType().ToString().Contains("ValidateException"))
                {
                    NLogHelper.LogError($"\r\n错误位置:\r\n所属类:{this.GetType().Name}\r\n方法名:{ methodName}\r\n{data.Msg}", data.Excep);
                    data.Msg = "系统错误！";
                }
                else
                {
                    data.Msg = data.Excep.Message.ToString();
                }
            }
            return File(data.fileContents, data.contentType);
        }


        /// <summary>
        /// 输出到客户端
        /// </summary>
        /// <param name="data"></param>
        protected ActionResult ReturnAction(ResultActionInfo data)
        {
            MethodBase methodName = new StackTrace().GetFrame(1).GetMethod();
            if (!data.Success)
            {
                if (!data.Excep.GetType().ToString().Contains("ValidateException"))
                {
                    NLogHelper.LogError($"\r\n错误位置:\r\n所属类:{this.GetType().Name}\r\n方法名:{ methodName}\r\n{data.Msg}", data.Excep);
                    data.Msg = "系统错误！";
                }
                else
                {
                    data.Msg = data.Excep.Message.ToString();
                }
            }
            if (data.RedirectPath != null && !data.RedirectPath.IsNotNullOrEmpty())
            {
                return Redirect(data.RedirectPath);
            }
            return View();
        }
        #endregion

        #region 其他逻辑处理


        #endregion

    }
}
